package geektime.im.lecture.ws.performance;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.prometheus.client.Gauge;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;


@ChannelHandler.Sharable
public class MetricsHandler extends ChannelDuplexHandler {

    private AtomicLong totalConnectionNumber = new AtomicLong();

    Gauge totalConnectionNumberGauge = Gauge.build()
            .name("rope_totalConnectionNumber")
            .help("当前有多少客户端TCP连接数")
            .register();

    {



       /* MetricRegistry metricRegistry = new MetricRegistry();

        metricRegistry.register("totalConnectionNumber", new Gauge<Long>() {
            @Override
            public Long getValue() {
                return totalConnectionNumber.longValue();
            }
        });

        ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry).build();
        consoleReporter.start(60, TimeUnit.SECONDS);*/

        /*JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();*/

    }

    /**
     * 连接建立-> 下发时间
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //com.didano.tcpserver.tcp.RopeSkippingProtocolDecoder.channelActive 没有触发。。。
//        ctx.channel().attr(AttributeKey.valueOf("count")).set(1);
//        totalConnectionNumber.incrementAndGet();
        totalConnectionNumberGauge.inc();
        System.out.println(totalConnectionNumberGauge.get());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        totalConnectionNumber.decrementAndGet();
        totalConnectionNumberGauge.dec();
        System.out.println("inActive: " + totalConnectionNumberGauge.get());
        super.channelInactive(ctx);
    }
}
